package com.xiaoxin.experience.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Objects;

/**
 * <p>Simple life, simple work, don't complicate</p>
 *
 * @author 小心
 * @version 1.0.0
 * @date 2021/8/16
 */
@Slf4j
public class IOUtil {

    private IOUtil() {}

    /**
     * 从输入流中获取字节数组
     */
    public static byte[] readInputStream(InputStream inputStream)
    {
        byte[] buffer = new byte[1024];
        int len;
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream())
        {
            while ((len = inputStream.read(buffer)) != -1)
            {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        }
        catch (IOException e)
        {
            return null;
        }
    }

    public static void close(Closeable closeable)
    {
        if (Objects.nonNull(closeable))
        {
            try
            {
                closeable.close();
            }
            catch (IOException e)
            {
                log.error("io stream close fail: ",e);
            }
        }
    }
}
